package com.alander.nexusgo.framework.mysql.starter.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Component
public class BaseEntityMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        if (metaObject.hasSetter("createTime")) {
            this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        }
        if (metaObject.hasSetter("updateTime")) {
            this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        }

        String createBy = resolveLoginIdOrSystem();
        if (metaObject.hasSetter("createBy")) {
            this.strictInsertFill(metaObject, "createBy", String.class, createBy);
        }
        if (metaObject.hasSetter("updateBy")) {
            this.strictInsertFill(metaObject, "updateBy", String.class, createBy);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (metaObject.hasSetter("updateTime")) {
            this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        }

        String updateBy = resolveLoginIdOrSystem();
        if (metaObject.hasSetter("updateBy")) {
            this.strictUpdateFill(metaObject, "updateBy", String.class, updateBy);
        }
    }

    private String resolveLoginIdOrSystem() {
        try {
            Class<?> stpUtil = Class.forName("cn.dev33.satoken.stp.StpUtil");
            Method m = stpUtil.getMethod("getLoginIdAsString");
            Object v = m.invoke(null);
            if (v != null) {
                return v.toString();
            }
        } catch (Throwable ignored) {
        }
        return "system";
    }
}